package com.ruoci.redis.bloomfilter;

import com.google.common.base.Charsets;
import com.google.common.hash.BloomFilter;
import com.google.common.hash.Funnels;
import com.ruoci.redis.response.BasicResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author yang
 * guava 实现布隆过滤器(缓存穿透-访问缓存和数据库都不存在的数据)
 **/
@Slf4j
@RestController
@RequestMapping("/guava")
public class GuavaController {


    /**
     * 实现布隆过滤器
     * @return
     */
    @GetMapping("/filter")
    public BasicResponse filter(){
        // 总数量1W
        int total = 10000;
        // 设置过滤器
        BloomFilter<CharSequence> bf = BloomFilter.create(Funnels.stringFunnel(Charsets.UTF_8), total,0.0147d);
        // 初始化 1W条数据到过滤器中
        for (int i = 0; i < total; i++) {
            bf.put("userInfo" + i);
        }
        // 判断值是否存在过滤器中
        int count = 0;
        // 插入2w 条数据进行去重校验
        int addCount = 2*total;
        for (int i = 0; i < addCount; i++) {
            if (bf.mightContain("userInfo" + i)) {
                count++;
            }
        }
        return BasicResponse.success("匹配数量".concat(String.valueOf(count)));
    }
}
